package com.alibaba.cloud.medicine.service.impl;

import com.alibaba.cloud.medicine.constant.MedConstant;
import com.alibaba.cloud.medicine.dao.MedItemMapper;
import com.alibaba.cloud.medicine.dto.MedItemDTO;
import com.alibaba.cloud.medicine.entity.MedItem;
import com.alibaba.cloud.medicine.service.MedItemService;
import com.alibaba.framework.exception.BusinessException;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class MedItemServiceImpl implements MedItemService {

    @Autowired
    private MedItemMapper medItemMapper;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public List<MedItem> getAll() {

        Wrapper<MedItem> wrapper = new QueryWrapper<>();
        List<MedItem> clinicOrderList = medItemMapper.selectList(wrapper);
        return clinicOrderList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(MedItemDTO medItemDTO) {
        validateMedItem(medItemDTO.getMedName());
        MedItem medItem = new MedItem();
        medItem.setCreateTime(new Date());
        BeanUtils.copyProperties(medItemDTO, medItem);

        medItemMapper.insert(medItem);
    }

    /**
     * @descript 药品扣减库存
     * @author focus
     * @date 2025/10/14
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deductStock(String medCode, Integer medStock) {
        int i = 0;
        RLock lock = redissonClient.getLock(MedConstant.MED_STOCK_LOCK_KEY + medCode);
        try {
            boolean bool = lock.tryLock(120, 10, TimeUnit.SECONDS);
            if (!bool) {
                throw new BusinessException("药品库存处理中，请勿重复提交");
            }
            QueryWrapper<MedItem> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("med_code", medCode);
            MedItem medItem = medItemMapper.selectOne(queryWrapper);
            if (Objects.isNull(medItem)) {
                throw new BusinessException("药品不存在");
            }
            Integer stock = medItem.getMedStock();
            if (stock < 1) {
                throw new BusinessException("库存不足!");
            }

            i = medItemMapper.deductStock(medCode, medStock);
            if (i < 0) {
                throw new BusinessException("修改库存失败！");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return i;
    }

    /**
     * @descript 校验药品名是否重复
     * @author focus
     * @date 2025/10/27
     */
    private void validateMedItem(String medName) {
        QueryWrapper<MedItem> wrapper = new QueryWrapper<>();
        wrapper.eq("med_name", medName);
        MedItem medItem = medItemMapper.selectOne(wrapper);
        if (!Objects.isNull(medItem)) {
            throw new BusinessException("药品已存在");
        }
    }
}
